using DevExpress.XtraPrinting.BarCode;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Printing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.Entity;
using static DevExpress.XtraEditors.Mask.MaskSettings;

namespace twistmachinev2
{
    /// <summary>
    /// 基础配置类 用于配置和数据传输
    /// </summary>
    public class BaseData
    {

        public static string PLCCOM = "";
        public static string IntervalSecond = "";
        public static string BarcodeCopies = "";
        public static string PrinterName = "";
        public static string TemplateName = "";

        public static string UseIntervalue = "";
        public static string ProduceLineNo = "";//生产线
        public static string WorkerClass = "";//班组
        public static string AutoWorkerClass = "";//是否启用自动班组
       // public static string SystemName = "";//系统名称
        //保存用户信息的
        //public static PUser SavedPuser;
        //public static string WorkStation;//工位名称
        public static string SystemBasicPath;//系统基础路径，为了解决图片存储和显示
        public static string AutoLunchTest;
        public static string TestItem = "";//测试项目

        // 当前登录用户信息
        public static PUser CurrentUser { get; set; }

        // 用户是否已登录
        public static bool IsUserLoggedIn => CurrentUser != null;

        // 获取当前用户权限级别
        public static long CurrentUserPermission => CurrentUser?.Permissionvalue ?? 0;

        // 获取当前用户名
        public static string CurrentUserName => CurrentUser?.UserName ?? "未登录";

        // 获取当前用户ID
        public static string CurrentUserId => CurrentUser?.UserId ?? "";

        // 清除用户登录信息（用于退出登录）
        public static void ClearUserInfo()
        {
            CurrentUser = null;

        }

        public static string[] SystemSerialPorts()
        {
            return SerialPort.GetPortNames();
        }

        //获取系统所有的打印机信息
        private static PrintDocument fPrintDocument = new PrintDocument();
        public static String DefaultPrinter
        {
            get { return fPrintDocument.PrinterSettings.PrinterName; }
        }

        public static string MESAPI { get; internal set; }
        public static string PrintAfterTest { get; internal set; }
        public static string ClearDate { get; internal set; }
        public static string TorqueBrand { get; internal set; }

        public static string TorqueIpAddress { get; internal set; }
        public static string TorquePort { get; internal set; }
        public static string MIDVersion { get; internal set; }

        public static string UsedMES { get; internal set; }

        public static string UsedSqlite { get; internal set; }

        public static string ScanBarcode { get; internal set; }

        // 数据库连接字符串配置
        private static string _opcuaDatabaseConnectionString;

        /// <summary>
        /// 获取OPCUA数据库连接字符串
        /// </summary>
        public static string OPCUADatabaseConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_opcuaDatabaseConnectionString))
                {
                    try
                    {
                        _opcuaDatabaseConnectionString = ConfigurationManager.ConnectionStrings["OPCUADatabase"]?.ConnectionString;
                        if (string.IsNullOrEmpty(_opcuaDatabaseConnectionString))
                        {
                            // 如果配置文件中没有找到，使用默认路径
                            _opcuaDatabaseConnectionString = "Data Source=D:\\J数据库\\SqliteDataBase\\双绞线\\data.db;Pooling=true;";
                        }
                    }
                    catch (Exception ex)
                    {
                        // 配置读取失败时使用默认路径
                        _opcuaDatabaseConnectionString = "Data Source=D:\\J数据库\\SqliteDataBase\\双绞线\\data.db;Pooling=true;";
                        System.Diagnostics.Debug.WriteLine($"读取数据库配置失败: {ex.Message}");
                    }
                }
                return _opcuaDatabaseConnectionString;
            }
        }

        /// <summary>
        /// 获取OPCUA数据库文件路径
        /// </summary>
        public static string OPCUADatabasePath
        {
            get
            {
                try
                {
                    var connectionString = OPCUADatabaseConnectionString;
                    // 从连接字符串中提取Data Source路径
                    var parts = connectionString.Split(';');
                    foreach (var part in parts)
                    {
                        if (part.Trim().StartsWith("Data Source=", StringComparison.OrdinalIgnoreCase))
                        {
                            return part.Substring(part.IndexOf('=') + 1).Trim();
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"提取数据库路径失败: {ex.Message}");
                }
                return "D:\\J数据库\\SqliteDataBase\\双绞线\\data.db";
            }
        }

        /// <summary>
        /// 获取系统名称配置
        /// </summary>
        /// <returns>系统名称</returns>
        public static string GetSystemName()
        {
            try
            {
                return ConfigurationManager.AppSettings["SystemName"] ?? "未设置系统名称";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取系统名称配置失败: {ex.Message}");
                return "未设置系统名称";
            }
        }

        /// <summary>
        /// 获取OPCUA数据库配置
        /// </summary>
        /// <returns>OPCUA数据库连接字符串</returns>
        public static string GetOPCUADatabaseConfig()
        {
            try
            {
                return ConfigurationManager.ConnectionStrings["OPCUADatabase"]?.ConnectionString ?? "未设置数据库连接";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取OPCUA数据库配置失败: {ex.Message}");
                return "未设置数据库连接";
            }
        }

        /// <summary>
        /// 读取App.config中的AppSettings配置项
        /// </summary>
        /// <param name="key">配置项键名</param>
        /// <returns>配置项值</returns>
        public static string ReadAppSetting(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key] ?? string.Empty;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取配置项 {key} 失败: {ex.Message}");
                return string.Empty;
            }
        }

        /// <summary>
        /// 修改App.config中的AppSettings配置项
        /// </summary>
        /// <param name="key">配置项键名</param>
        /// <param name="value">配置项值</param>
        /// <returns>是否修改成功</returns>
        public static bool UpdateAppSetting(string key, string value)
        {
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                
                if (config.AppSettings.Settings[key] != null)
                {
                    config.AppSettings.Settings[key].Value = value;
                }
                else
                {
                    config.AppSettings.Settings.Add(key, value);
                }
                
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"修改配置项 {key} 失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 修改App.config中的ConnectionStrings配置项
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="providerName">提供程序名称</param>
        /// <returns>是否修改成功</returns>
        public static bool UpdateConnectionString(string name, string connectionString, string providerName = "System.Data.SQLite")
        {
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                
                if (config.ConnectionStrings.ConnectionStrings[name] != null)
                {
                    config.ConnectionStrings.ConnectionStrings[name].ConnectionString = connectionString;
                    config.ConnectionStrings.ConnectionStrings[name].ProviderName = providerName;
                }
                else
                {
                    config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, connectionString, providerName));
                }
                
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("connectionStrings");
                
                // 清除缓存的连接字符串
                if (name == "OPCUADatabase")
                {
                    _opcuaDatabaseConnectionString = null;
                }
                
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"修改连接字符串 {name} 失败: {ex.Message}");
                return false;
            }
        }
        public static List<String> GetLocalPrinters()
        {
            List<String> fPrinters = new List<string>();
            fPrinters.Add(DefaultPrinter); // 默认打印机始终出现在列表的第一项  
            foreach (String fPrinterName in PrinterSettings.InstalledPrinters)
            {
                if (!fPrinters.Contains(fPrinterName))
                    fPrinters.Add(fPrinterName);
            }
            return fPrinters;
        }
        //获取系统模版下所有的文件信息
        public static IEnumerable<string> GetTemplates(string path)
        {
            var files = Directory.GetFiles(path, "*.frx");
            return files;
        }


        //获取图像信息
        public static String GetPicPath(string IntitialDirectory, OpenFileDialog openFileDialog)
        {
            string resultFile = "";
            openFileDialog.InitialDirectory = IntitialDirectory;
            openFileDialog.Filter = "All files (*.*)|*.*|产品图片|*.jpg|产品图片|*.png";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                resultFile = openFileDialog.FileName;
                return resultFile;

            }
            else
            {
                return "NoFile";
            }
        }
        //移动照片,将照片移动到文件夹当中
        public static void MoveFile(string oldFileName, string newFileName, string FileLocation)
        {


            string newLocationFileName = newFileName;
            FileInfo oldPic = new FileInfo(oldFileName);
            string fileExtension = ".jpg";//移动之后后缀名为.jpg
            //默认覆盖现有文件
            oldPic.CopyTo(Path.Combine(FileLocation, newFileName + fileExtension), true);


        }
        //删除文件
        public static void DeleteFile(string fileName)
        {
            if (File.Exists(fileName))
            {
                try
                {
                    File.Delete(fileName);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        }

    }
}
